package com.wan.middleware.zookeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.CuratorCache;
import org.apache.curator.framework.recipes.cache.CuratorCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Watcher;

import java.util.List;

/**
 * @author wwh
 * @date 2022/6/21 15:05
 */
public class ZookeeperClient {
    private final CuratorFramework client;

    /**
     * 创建一个连接
     */
    public ZookeeperClient(ZkConfig zkConfig) {
        client = CuratorFrameworkFactory.newClient(zkConfig.getAddress(),zkConfig.getSessionTimeout(),
                zkConfig.getConnectionTimeout(),
                new ExponentialBackoffRetry(3000, 10));//重试时间，次数)
        client.start();
    }

    public CuratorFramework getClient() {
        return client;
    }

    public String createPathData(String path, byte[] data, CreateMode createMode) throws Exception {
        return client.create().creatingParentsIfNeeded()
                .withMode(createMode)
                .forPath(path, data);
    }

    public void updatePathData(String path, byte[] data) throws Exception {
        client.setData().forPath(path, data);
    }

    public void deletePath(String path) throws Exception {
        client.delete().forPath(path);
    }

    /**
     * 监听指定节点内数据变化
     */
    public void watchNode(String path, Watcher watcher) throws Exception {
        client.getData().usingWatcher(watcher).forPath(path);
    }

    public byte[] getData(String path) throws Exception {
        return client.getData().forPath(path);
    }

    /**
     * 子节点目录
     */
    public List<String> getChildren(String path) throws Exception {
        return client.getChildren().forPath(path);
    }

    public void watchCuratorCache(String path, CuratorCacheListener listener) {
        CuratorCache curatorCache = CuratorCache.build(client, path);
        curatorCache.listenable().addListener(listener);
        curatorCache.start();
    }

    /**
     * 创建目录，存在不会创建
     */
    public void createPathIfNotExist(String path) throws Exception {
        client.checkExists().creatingParentsIfNeeded().forPath(path);
    }

    public void close() {
        client.close();
    }
}
